#!/bin/sh

#参数1 应用程序名称，如foxit-userspace-web
#参数2 应用域名，如userspace.foxitcloud.com

# 定义TOMCAT_HOME环境变量
if [ -z "$TOMCAT_HOME" ]; then
  TOMCAT_HOME=/usr/share/tomcat/apache-tomcat-7.0.41
fi
export TOMCAT_HOME

#程序参数定义
APP_FILE_NAME=$1
WAR_FILE_NAME="${APP_FILE_NAME}.war"
WAR_TMP_PATH=/tmp/$APP_FILE_NAME

SERVER_FILE=$TOMCAT_HOME/conf/server.xml
DOMAIN=$2
REPACE="<Host name=\"${DOMAIN}\" appBase=\"webapps/${APP_FILE_NAME}\" unpackWARs=\"true\" autoDeploy=\"true\"><Context docBase=\".\" path=\"\" /></Host>"
POSITION='<\/Engine>'

RetValue=0
service tomcat stop

rm -rf $TOMCAT_HOME/webapps/$WAR_FILE_NAME
rm -rf $TOMCAT_HOME/webapps/$APP_FILE_NAME
mv  $WAR_TMP_PATH/$WAR_FILE_NAME  $TOMCAT_HOME/webapps/

if [ ! -f "$TOMCAT_HOME/webapps/$WAR_FILE_NAME" ]; then
	echo "mv $WAR_FILE_NAME error."
	RetValue=1
fi

if [ $RetValue == 0 ]; then
	unzip -q $TOMCAT_HOME/webapps/$WAR_FILE_NAME -d $TOMCAT_HOME/webapps/$APP_FILE_NAME
	if [ $? != 0 ]; then
	  echo "unzip $WAR_FILE_NAME error."
	  RetValue=1
	fi
fi

if [ $RetValue == 0 ]; then
	sed -i "/$DOMAIN/d"  $SERVER_FILE
	if [ ! $? == 0 ]; then
		echo "($SERVER_FILE) remove $DOMAIN error."
		RetValue=1
	fi
fi

if [ $RetValue == 0 ]; then
	sed -i "/$POSITION/i $REPACE" $SERVER_FILE
	if [ ! $? == 0 ]; then
	  echo "add $DOMAIN error."
	  RetValue=1
	fi
fi

service tomcat start
echo "end deployWar:$APP_FILE_NAME"
exit $RetValue;
